package com.llh.test.connection;

import org.junit.Test;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * <h2>数据库连接测试</h2>
 * <p>用最原始的方法</p>
 * <p>CreatedAt: 2019-11-24 21:32</p>
 * <p><a href="mailto:forever2y_y@163.com">SendMailToMe</a></p>
 *
 * @author llh
 */
public class ConnectionTest01 {


    /**
     * 最原始的写法
     */
    @Test
    public void testConn01() throws SQLException {
        // 获取驱动
        Driver driver = new com.mysql.cj.jdbc.Driver();

        connectionDB(driver);

    }

    /**
     * 获取驱动方法二
     * 进一步的解耦了
     *
     * @throws Exception
     */
    @Test
    public void testConn02() throws Exception {
        Class driverName = Class.forName("com.mysql.cj.jdbc.Driver");
        Driver driver = (Driver) driverName.newInstance();
        connectionDB(driver);
    }

    /**
     * <p>使用DriverManager进行数据库连接</p>
     * <p>注册驱动这一步其实可以省略的,
     * {@link com.mysql.cj.jdbc.Driver}里有段静态代码块帮我们做了注册驱动这事儿。 </p>
     */
    @Test
    public void testConn03() throws Exception {
        Class driverName = Class.forName("com.mysql.cj.jdbc.Driver");
        Driver driver = (Driver) driverName.newInstance();
        DriverManager.registerDriver(driver);
        String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC";
        Properties info = new Properties();
        info.setProperty("user", "root");
        info.setProperty("password", "root");
        Connection connection = DriverManager.getConnection(url, info);
        System.out.println(connection);
    }

    /**
     * 使用配置文件进行连接
     */
    @Test
    public void testConn04() throws Exception {
        InputStream resourceAsStream = ConnectionTest01.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        properties.load(resourceAsStream);
        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url");
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println(connection);
    }


    /**
     * 因为会多次用到，就提取出来了
     *
     * @param driver 数据库驱动对象实例
     */
    private void connectionDB(Driver driver) throws SQLException {
        // 配置数据库信息
        // 我电脑上装的是MySQL8必须要指定serverTimezone的值
        String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC";
        Properties info = new Properties();
        info.setProperty("user", "root");
        info.setProperty("password", "root");
        //  建立连接
        Connection connect = driver.connect(url, info);
        System.out.println(connect);
    }
}
